package com.yaowen.xmlreader;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * Created by HelloWorld on 2015/9/22.
 */
public class SAXHandler extends DefaultHandler {
    String tagName;
    // 改进1：使用标识位来标识开始标签
    private boolean IsStartName = false;
    private boolean IsStartAge = false;
    private boolean IsStartWorlk = false;
    // 当有值存在时，就调用该方法解析取值（如果是空值，也会调用这个方法）

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        /*
         * String value= new String(ch, start,length);
		 * if(tagName.equals("name")) { System.out.println("name="+ value); }
		 * if(tagName.equals("age")) { System.out.println("age="+value); }
		 */
        // 改进2：使用在StartElement中赋值的标识位来判断是否取值
        if (IsStartName) {
            System.out.println("名字：" + new String(ch, start, length));
        } else if (IsStartAge) {
            System.out.println("年龄：" + new String(ch, start, length));
        }
    }

    @Override
    public void endDocument() throws SAXException {
        System.out.println("---------------end-------------");
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {

        if (localName.equals("work")) {
            IsStartWorlk = false;
            System.out.println("-------end----work--------");
        }
        if (localName.equals("name")) {
            IsStartName = false;
        }
        if (localName.equals("age")) {
            IsStartAge = false;
        }
    }

    @Override
    public void startDocument() throws SAXException {
        System.out.println("-----------begin----------");
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

        tagName = localName;
        if (localName.equals("work")) {
            IsStartWorlk = true;
            for (int i = 0; i < attributes.getLength(); i++) {
                System.out.println(attributes.getLocalName(i) + "="
                        + attributes.getValue(i));
            }
        }
        if (localName.equals("name")) {
            IsStartName = true;
        }
        if (localName.equals("age")) {
            IsStartAge = true;
        }
    }
}
